package cn.wit.summit.chwan.ui.service;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;

import com.google.gson.Gson;

import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.Stat.StatFactory;
import cn.wit.summit.chwan.models.db.DownLoadTaskTable;
import cn.wit.summit.chwan.models.dbmanager.DownloadTaskManager;
import cn.wit.summit.chwan.models.dto.GameInfoDetial;
import cn.wit.summit.chwan.models.event.DownloadEvent;
import cn.wit.summit.chwan.net.BuildRequestUtils;
import cn.wit.summit.chwan.net.okhttplib.HttpInfo;
import cn.wit.summit.chwan.net.okhttplib.OkHttpUtil;
import cn.wit.summit.chwan.net.okhttplib.callback.Callback;
import cn.wit.summit.chwan.tools.downloadtool.DownLoadStatusConfig;
import cn.wit.summit.chwan.tools.downloadtool.DownloadTool;
import cn.wit.summit.chwan.ui.activity.MainActivity;
import cn.wit.summit.chwan.ui.base.MyApplication;
import cn.wit.summit.chwan.utils.APKUtils;
import cn.wit.summit.chwan.utils.LogUtils;
import cn.wit.summit.chwan.utils.NetWorkUtils;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.utils.UtilsMy;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

/**
 * Created by pengsk on 2018/4/9.
 */

public class ChWService extends Service {
    Context context;
    InstallChangeReceiver receiver;
    WifiChangeReceiver wifiChangeReceiver;

    public void useForeground(CharSequence tickerText, String currSong) {
        Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);
        /* Method 01
         * this method must SET SMALLICON!
         * otherwise it can't do what we want in Android 4.4 KitKat,
         * it can only show the application info page which contains the 'Force Close' button.*/
        NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(ChWService.this)
                .setSmallIcon(R.drawable.main_normal_icon)
                .setTicker(tickerText)
                .setWhen(System.currentTimeMillis())
                .setContentTitle(getString(R.string.app_name))
                .setContentText(currSong)
                .setContentIntent(pendingIntent);
        Notification notification = mNotifyBuilder.build();

    /* Method 02
    Notification notification = new Notification(R.drawable.ic_launcher, tickerText,
            System.currentTimeMillis());
    notification.setLatestEventInfo(PlayService.this, getText(R.string.app_name),
            currSong, pendingIntent);
    */

        startForeground(1, notification);
    }

    @Override
    public void onCreate() {
        super.onCreate();
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            useForeground("超会玩", "超会玩的服务");
//        }
        EventBus.getDefault().register(this);
        IntentFilter filter = new IntentFilter();
//        filter.addAction(BroadcastAction.ACTION_INSTALL_BROADCAST_RESVERED);
        filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
        filter.addAction(Intent.ACTION_PACKAGE_ADDED);
        filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
        filter.addDataScheme("package");
        receiver = new InstallChangeReceiver();
        registerReceiver(receiver, filter);

        IntentFilter filterWifi = new IntentFilter();
        filterWifi.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filterWifi.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filterWifi.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        filterWifi.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        wifiChangeReceiver = new WifiChangeReceiver();
        registerReceiver(wifiChangeReceiver, filterWifi);
        context = this;

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        MyApplication.serviceHasRouning = true;
        if (intent != null && StringUtils.isNotEmpty(intent.getStringExtra("downGameId"))) {
            getGameInfoData(intent.getStringExtra("downGameId"));
        } else {
            if (NetWorkUtils.isWifiConnected(context)) {
                List<DownLoadTaskTable> downLoadTaskTables = DownloadTaskManager.getInstance().findAllGame();
                for (DownLoadTaskTable table : downLoadTaskTables) {
                    if (table.getDownStatus() == DownLoadStatusConfig.DOWNLOADING || table.getDownStatus() == DownLoadStatusConfig.WAIT) {
                        DownloadTool.downloadGame(this, table, null);
                    }
                }
            } else {
                List<DownLoadTaskTable> downLoadTaskTables = DownloadTaskManager.getInstance().findAllGame();
                for (DownLoadTaskTable table : downLoadTaskTables) {
                    if (table.getDownStatus() == DownLoadStatusConfig.DOWNLOADING || table.getDownStatus() == DownLoadStatusConfig.WAIT) {
                        table.setDownStatus(DownLoadStatusConfig.DOWNLOAD_ERROR);
                        DownloadTaskManager.getInstance().updateStatusBygameId(table.getGameId(), DownLoadStatusConfig.DOWNLOAD_ERROR);
                    }
                }
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }


    private void getGameInfoData(String gameId) {
        OkHttpUtil.getDefault(this).doPostAsync(BuildRequestUtils.getInstance(this).getGameDetialData(gameId, 0), new Callback() {
            @Override
            public void onCache(HttpInfo info) throws IOException {

            }

            @Override
            public void onSuccess(HttpInfo info) throws IOException {
                String json = info.getRetDetail();
                GameInfoDetial detial = new Gson().fromJson(json, GameInfoDetial.class);
//                ResultMainBean<List<GameInfoDetial>> detial2= new Gson().fromJson(json,GameInfoDetial.class);new
                DownLoadTaskTable taskTable = detial.getDownloadTaskTable();
                DownloadTool.downloadGame(context, taskTable, null);

            }

            @Override
            public void onFailure(HttpInfo info) throws IOException {

            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (receiver != null)
            unregisterReceiver(receiver);
        if (wifiChangeReceiver != null)
            unregisterReceiver(wifiChangeReceiver);
        EventBus.getDefault().unregister(this);
        MyApplication.serviceHasRouning = false;
        LogUtils.e("CHWService ondestroy");
    }

    //自定义接受网络变化的广播接收器
    class InstallChangeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
//            String packageName = intent.getStringExtra("packageName");
//            String actionFrom = intent.getStringExtra("actionFrom");
            String packageName = intent.getData().getSchemeSpecificPart();
            ;
            String actionFrom = intent.getAction();
            if (actionFrom.equals(Intent.ACTION_PACKAGE_ADDED)) {
                changeDownloadState(1, packageName);
            } else if (actionFrom.equals(Intent.ACTION_PACKAGE_REMOVED)) {
                changeDownloadState(4, packageName);
            } else if (actionFrom.equals(Intent.ACTION_PACKAGE_REPLACED)) {
                changeDownloadState(1, packageName);
            }
        }
    } //自定义接受网络变化的广播接收器

    private static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    boolean isWifi = false;

    class WifiChangeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(final Context context, Intent intent) {
            LogUtils.e("WifiChangeReceiver  " + intent.getAction());
            String action = intent.getAction();
            if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action) || action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION) || action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                boolean isConnected = NetWorkUtils.isNetworkConnected(context);

                if (NetWorkUtils.isWifiConnected(context)) {
                    isWifi = true;
                } else {

                    isWifi = false;
                }
//                retryOnSomeTime();

                //如果已经连接着网络并且是wifi网络
                if (isWifi) {
                    scheduler.execute(new Runnable() {
                        @Override
                        public void run() {
                            if (NetWorkUtils.ping()) {
                                List<DownLoadTaskTable> taskTables = DownloadTaskManager.getInstance().findAllDownloadFailed();
                                if (taskTables != null && taskTables.size() > 0) {
                                    for (DownLoadTaskTable taskTable : taskTables) {
                                        DownloadTool.downloadGame(context, taskTable, null);
                                    }
                                }
                            }
                        }
                    });

                } else {

                }

            }
        }
    }

    void changeDownloadState(int i, String packageName) {
        try {
            List<DownLoadTaskTable> downloadTasks = DownloadTaskManager.getInstance().findAllGame();

            for (DownLoadTaskTable downloadTask : downloadTasks) {
                if (packageName.equals(downloadTask.getPackageName())) {

//                    DownloadTask downloadTask1 = null;
                    switch (i) {
                        case 1://安装成功
                            if (downloadTask != null) {
                                downloadTask.setDownStatus(DownLoadStatusConfig.INSTALLED);
                                DownloadTaskManager.getInstance().updateStatusByPackageName(packageName, DownLoadStatusConfig.INSTALLED);

                                StatFactory.getInstance().sendGameInstall(context,downloadTask.getGameId(),1+"");
                            }
                            EventBus.getDefault().post(downloadTask.getDownEvent());
                            //如果安装完成apk后删除apk包。
                            try {
                                File file = new File(downloadTask.getDownPath());
                                if (file.exists()) {
                                    UtilsMy.delete(file);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                            break;
                        case 4://被卸载
                            if (downloadTask == null) return;
                            StatFactory.getInstance().sendGameInstall(context,downloadTask.getGameId(),4+"");
                            DownloadTool.deletTask(downloadTask);
                            break;

                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DownloadEvent downloadEvent) {

        if (downloadEvent.getStatus() == DownLoadStatusConfig.DOWNLOAD_FINISH) {
            //do install
            DownLoadTaskTable downLoadTaskTable = DownloadTaskManager.getInstance().findByGameId(downloadEvent.gameId);
            switch (downLoadTaskTable.getGameType()) {
                case 0:
                    StatFactory.getInstance().sendGameDownLoadDone(context, downloadEvent.gameId);
                    downloadEvent.setStatus(DownLoadStatusConfig.INSTALL_WAIT);
                    EventBus.getDefault().post(downloadEvent);
                    DownloadTaskManager.getInstance().updateStatusBygameId(downloadEvent.gameId, DownLoadStatusConfig.INSTALL_WAIT);
                    APKUtils.getInstance(context).installAPK(context, downLoadTaskTable.getDownPath(), downloadEvent.gameId);
                    break;
                case 1:
                case 2:
                    StatFactory.getInstance().sendUnZip(this,downloadEvent.getGameId(),3+"");
                    downloadEvent.setStatus(DownLoadStatusConfig.UNZIP_WAIT);
                    EventBus.getDefault().post(downloadEvent);
                    DownloadTaskManager.getInstance().updateStatusBygameId(downloadEvent.gameId, DownLoadStatusConfig.UNZIP_WAIT);
                    DownloadTool.unzip(context, downLoadTaskTable);
                    break;
            }

        } else {

        }

    }
}
